<!-- 数据分发 -->
<script setup lang="ts">
import {
  useMessage,
  NButton,
  NSpace,
  NDataTable,
  NInput,
  type DataTableColumns,
  type DataTableRowKey,
  NPagination,
  NModal,
  NForm,
  NFormItem,
  NSelect,
  NCheckbox,
  NCheckboxGroup,
  NRadio,
  NRadioGroup,
  NPopconfirm
} from 'naive-ui'
import type { FormInst } from 'naive-ui'
import { onActivated, onMounted, reactive, ref, h, watch, onDeactivated } from 'vue'
import { sendRequest } from '@/utils/api'
import type { clueModel } from '@/api/clue'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'
import TableView from '@/components/TableView.vue'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { useRoute, useRouter } from 'vue-router'
import choiceComponent from '@/views/DataTranslate/Translate/choiceComponent.vue'
const message = useMessage()
const router = useRouter()
const listOption = ref([])
onActivated(() => {
  if (window.flags.flushRole) {
    queryTableData(true)
    window.flags.flushRole = false
  }
})
const formValue = ref({
  source: null,
  dataDestination: null
})
const rules = {
  dataDestination: {
    required: true,
    message: '请选择去向',
    type: 'array',
    trigger: ['change']
  },
  source: {
    required: true,
    message: '请选择数据来源',
    trigger: ['change', 'input', 'blur']
  }
}
const choiceVisible = ref(false)
const formRef = ref<FormInst | null>(null)
const tableData = ref()
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})
type Reset = () => void
function useQueryForm<T = unknown>(form: T, reset: Reset): [form: T, reset: Reset] {
  return [form, reset]
}
const modalVisible = ref(false)
const route = useRoute()
const [form, resetForm] = useQueryForm(
  reactive({
    important: null,
    methodCode: null,
    collectionName: null
  }),
  () => {
    form.important = null
    form.methodCode = null
    form.collectionName = null
  }
)
// 1
const columns: DataTableColumns<clueModel> = [
  {
    type: 'selection',
    width: '2rem'
  },
  {
    title: '藏品名称',
    key: 'collectionName',
    width: '10rem',
    align: 'center',
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '馆藏码',
    key: 'assetCode',
    width: '5rem',
    align: 'center'
  },
  {
    title: '数据去向',
    key: 'dataDestination',
    width: '5rem',
    align: 'center'
  },
  {
    title: '来源',
    key: 'method',
    width: '3rem',
    align: 'center',
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '征集时间',
    key: 'collectionTime',
    width: '5rem',
    align: 'center',
    ellipsis: {
      tooltip: true
    },
    render: (e: any) => {
      return e?.collectionTime?.split(' ')?.[0]
    }
  },
  {
    title: '编目时间',
    key: 'catalogingTime',
    width: '5rem',
    align: 'center',
    render: (e: any) => {
      return e?.catalogingTime?.split(' ')?.[0]
    }
  },

  {
    title: '接收人',
    key: 'receiver',
    width: '5rem',
    align: 'center',
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '状态',
    key: 'isEnable',
    width: '2rem',
    align: 'center',
    render: (e: any) => {
      return e.isEnable ? '启用' : '停用'
    }
  },
  {
    title: '操作',
    key: 'action',
    width: '10rem',
    align: 'center',
    fixed: 'right',
    render: (e: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => handleEdit(e),
          style: {
            display: !e.editFlag ? 'inline-block' : 'none'
          }
        },
        {
          default: () => '编辑'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => handleDetail(e)
        },
        {
          default: () => '详情'
        }
      ),
      h(
        NPopconfirm,
        {
          onPositiveClick: () => handleEnable(e.isEnable ? 0 : 1, e),
          negativeText: '取消',
          positiveText: '确定'
        },
        {
          default: () => `确定${e.isEnable == 1 ? '停用' : '启用'}？`,
          trigger: () =>
            h(
              NButton,
              { type: 'primary', quaternary: true },
              {
                default: () => (e.isEnable == 1 ? '停用' : '启用')
              }
            )
        }
      ),
      h(
        NButton,
        {
          type: 'error',
          quaternary: true,
          onClick: () => handleDelete(e.id),
          style: {
            display: e.statusName === '已确认' ? 'none' : 'inline-block'
          }
        },
        {
          default: () => '删除'
        }
      )
    ]
  }
]
const rowKey: any = (e: any) => e.id || ''
const checkedRowKeysRef = ref<DataTableRowKey[]>([])
const tableLoading = ref(false)
const queryTableData = async (resetPage = false) => {
  checkedRowKeysRef.value = []
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponsePagination<clueModel>>({
    module: 'dataDistribution',
    api: 'list',
    override: {
      params: {
        important: form.important,
        methodCode: form.methodCode,
        collectionName: form.collectionName,
        page: paginationReactive.page,
        limit: paginationReactive.pageSize
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  paginationReactive.itemCount = res.data.totalCount
  tableData.value = res.data.list
}
const handleCheck = (rowKeys: DataTableRowKey[]) => {
  checkedRowKeysRef.value = rowKeys
}
//下拉
const getFunction = async () => {
  listOption.value = []
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'clue',
    api: 'listByParentCode',
    override: {
      params: {
        dicCode: 'A62'
      }
    }
  })
  if (error) return message.error(error.message)
  res.data.forEach((i: any) => {
    // @ts-ignore
    listOption.value.push({ label: i.dicName, value: i.dicCode })
  })
}
const handleEdit = (e: any) => {
  router.push({
    name: 'dataTranslateEidt',
    params: { id: e.id },
    query: {
      redirect: route.fullPath
    }
  })
}
const handleDetail = (e: any) => {
  router.push({
    name: 'dataTranslateDetail',
    params: { id: e.id },
    query: {
      disabled: true,
      redirect: route.fullPath
    }
  })
}
const handleAdd = () => {
  addVisible.value = true
  // router.push({
  //   name: 'clueManagementAdd',
  //   query: {
  //     redirect: route.fullPath
  //   }
  // })
}
/**
 * 启用停用
 */
const handleEnable = async (isEnable: number, row: any = {}) => {
  let ids = []
  if (row.id) ids = [row.id]
  else ids = checkedRowKeysRef.value
  const [error, res] = await sendRequest({
    module: 'dataDistribution',
    api: 'enable',
    override: {
      data: {
        ids,
        isEnable
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  message.success(`${row.isEnable == 1 ? '停用' : '启用'}成功`)
  tableData.value = []
  setTimeout(() => {
    queryTableData()
  }, 0)
}
const ids = ref()
const handleDelete = (id: any) => {
  ids.value = id
  modalVisible.value = true
}
const addVisible = ref(false)
const addBefore = () => {
  formRef.value?.validate(async (err: any) => {
    if (err) return
    if (formValue.value.source == '1') {
      // 新增
      router.push({
        name: 'dataTranslateAdd',
        query: {
          dataDestination: formValue.value.dataDestination?.join(','),
          redirect: route.fullPath
        }
      })
      formValue.value.dataDestination = null
      formValue.value.source = null
    } else {
      choiceVisible.value = true
    }

    addVisible.value = false
  })
}
const choiceItems = ref([])
const setItemNamesFn = (item: any) => {
  choiceItems.value = item.map((it: any) => it.id)
}
const submit = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'dataDistribution',
    api: 'saveBatch',
    override: {
      data: JSON.parse(
        JSON.stringify({
          dataDestination: formValue.value.dataDestination?.join(','),
          ids: choiceItems.value
        })
      )
    }
  })
  if (error) return message.error(error.message)
  formValue.value.dataDestination = null
  formValue.value.source = null
  choiceVisible.value = false
  queryTableData(true)
}
const againDelete = async () => {
  const [error] = await sendRequest<HttpResponse>({
    module: 'dataDistribution',
    api: 'delete',
    override: {
      data: [ids.value]
    }
  })
  if (error) return message.error(error.message)
  queryTableData(true)
  modalVisible.value = false
}
const isAdd = ref(false)
const queryCheckUserInZjb = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'collectNotice',
    api: 'checkUserInZjb'
  })
  if (error) return message.error(error.message)
  isAdd.value = res.data
}
const collectFactionList = ref()
// 字典下拉
const codeFn = async (code: any, refValue: any) => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'listByParentCode',
    override: {
      params: {
        dicCode: code
      }
    }
  })
  if (error) return message.error(error.message)
  refValue.value = res?.data?.map((it: any) => {
    return { value: it.dicCode, label: it.dicName }
  })
}
onMounted(() => {
  getFunction()
  queryCheckUserInZjb()
  // queryTableData(true)
  codeFn('A30', collectFactionList) //来源A30
})
const keyUpDown = (e: any) =>
  e.key == 'Enter' && ((paginationReactive.page = 1), queryTableData(true))
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))
watch(
  () => route,
  () => {
    if (route.path == '/dataTranslate/translate/index') {
      queryTableData(true)
      window.addEventListener('keyup', keyUpDown, false) // 回车
    }
  },
  { deep: true, immediate: true }
)
</script>

<template>
  <TableView class="role">
    <template #form>
      <NForm
        :show-feedback="false"
        label-placement="left"
        inline
      >
        <NFormItem label="藏品名称:">
          <NInput
            placeholder="请输入"
            v-model:value="form.collectionName"
          />
        </NFormItem>
        <NFormItem label="来源:">
          <!-- 来源就是征集方式 -->
          <NSelect
            :options="collectFactionList"
            v-model:value="form.methodCode"
            placeholder="请选择来源"
            clearable
            filterable
            style="width: 200px"
          />
        </NFormItem>
        <NFormItem label="重要藏品:">
          <NSelect
            :options="[
              { value: '是', label: '是' },
              { value: '否', label: '否' }
            ]"
            v-model:value="form.important"
            placeholder="请选择重要藏品"
            clearable
            style="width: 200px; margin-right: 20px"
          />
        </NFormItem>
        <NSpace>
          <NButton
            type="primary"
            style="width: 78px; margin-right: 10px"
            ghost
            @click="queryTableData(true)"
            :loading="tableLoading"
          >
            查询
          </NButton>
          <NButton
            type="primary"
            ghost
            style="width: 78px; margin-right: 10px"
            @click="resetForm"
          >
            重置
          </NButton>
          <NButton
            color="#5FB17F"
            ghost
            @click="() => handleEnable(1)"
            :disabled="checkedRowKeysRef.length ? false : true"
          >
            批量启用
          </NButton>
          <NButton
            color="red"
            ghost
            @click="() => handleEnable(0)"
            :disabled="checkedRowKeysRef.length ? false : true"
          >
            批量停用
          </NButton>
          <NButton
            type="primary"
            style="width: 115px"
            @click="handleAdd"
            v-if="isAdd"
          >
            新增
          </NButton>
        </NSpace>
      </NForm>
    </template>
    <template #table="props">
      <NDataTable
        v-bind="props"
        :data="tableData"
        :columns="columns"
        :row-key="rowKey"
        :loading="tableLoading"
        size="small"
        :bordered="false"
        @update:checked-row-keys="handleCheck"
        :checked-row-keys="checkedRowKeysRef"
      />
    </template>
    <template #pagination>
      <NPagination
        :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker
        show-quick-jumper
        :suffix="() => '页'"
      >
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>
  <NModal
    :auto-focus="false"
    v-model:show="modalVisible"
  >
    <VDialogContent
      @close="modalVisible = false"
      @submit="againDelete"
      title="删除提示"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要删除吗?
      </div>
    </VDialogContent>
  </NModal>
  <NModal
    :auto-focus="false"
    v-model:show="addVisible"
  >
    <VDialogContent
      @close="
        () => {
          addVisible = false
          formValue.dataDestination = null
          formValue.source = null
        }
      "
      @submit="addBefore"
      title="藏品来源"
    >
      <div style="width: 350rem; height: 100rem; text-align: center; line-height: 100rem">
        <n-form
          ref="formRef"
          :model="formValue"
          :rules="rules"
          size="small"
          label-placement="left"
          label-width="120rem"
          require-mark-placement="left"
        >
          <n-form-item
            label="选择数据去向"
            path="dataDestination"
          >
            <n-checkbox-group v-model:value="formValue.dataDestination">
              <n-space item-style="display: flex;">
                <n-checkbox
                  value="B3大屏"
                  label="B3大屏"
                />
                <n-checkbox
                  value="互动查询"
                  label="互动查询"
                />
              </n-space>
            </n-checkbox-group>
          </n-form-item>
          <n-form-item
            label="选择数据来源"
            path="source"
          >
            <n-radio-group
              v-model:value="formValue.source"
              name="radiogroup"
            >
              <n-space>
                <n-radio
                  :key="1"
                  value="1"
                >
                  新增
                </n-radio>
                <n-radio
                  :key="2"
                  value="2"
                >
                  藏品管理
                </n-radio>
              </n-space>
            </n-radio-group>
          </n-form-item>
        </n-form>
      </div>
    </VDialogContent>
  </NModal>
  <NModal
    :auto-focus="false"
    v-model:show="choiceVisible"
    style="width: 95%"
  >
    <VDialogContent
      @close="choiceVisible = false"
      @submit="submit"
      title="藏品选择"
    >
      <choiceComponent
        @update="setItemNamesFn"
        @close="choiceVisible = false"
      />
    </VDialogContent>
  </NModal>
</template>

<style lang="scss" scoped>
.role {
  padding: 29rem 20rem 42rem 30rem;
  color: rgba(0, 0, 0, 0.85);
}
</style>
